package com.wechat.wins.util;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public final class CryptoUtils {

    private static final String KEY_ALGORITHM = "DES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
//	private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/ISO10126Padding";

    public static byte[] decrypt(final byte[] data, final Key key) throws Exception {
        return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    public static byte[] decrypt(final byte[] data, final byte[] key) throws Exception {
        return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    public static byte[] decrypt(final byte[] data, final byte[] key, final String algorithm) throws Exception {
        final Key key1 = toKey(key);
        return decrypt(data, key1, algorithm);
    }

    public static byte[] decrypt(final byte[] data, final Key key, final String algorithm) throws Exception {
        final Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    public static byte[] encrypt(final byte[] data, final byte[] key) throws Exception {
        return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    public static byte[] encrypt(final byte[] data, final byte[] key, final String algorithm) throws Exception {
        final Key key1 = toKey(key);
        return encrypt(data, key1, algorithm);
    }

    public static byte[] encrypt(final byte[] data, final Key key) throws Exception {
        return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
    }

    public static byte[] encrypt(final byte[] data, final Key key, final String algorithm) throws Exception {
        final Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    public static byte[] buildSecretKey(final SecureRandom secureRandom) throws Exception {
        //返回生成指定算法的秘密密钥的 KeyGenerator 对象
        final KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        //初始化此密钥生成器，使其具有确定的密钥大小
        kg.init(secureRandom);
        //生成一个密钥
        final SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    public static Key toKey(final byte[] desKey) throws Exception {
        //实例化DES密钥规则
        final DESKeySpec dks = new DESKeySpec(desKey);
        //实例化密钥工厂
        final SecretKeyFactory skf = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        //生成密钥
        final SecretKey  secretKey = skf.generateSecret(dks);
        return secretKey;
    }
}
